<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">

        <QueryFormItem label="状态标识">
          <MultipleSelect v-model="specialFlagList" :options="specialFlagOptions" placeholder="请选择状态标识"/>
        </QueryFormItem>

        <QueryFormItem label="注册时间">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          class="card-header-extra-action"
                          clearable
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          value-format="YYYY-MM-DD"/>
        </QueryFormItem>

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="content-card system-user">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
        <el-button v-permission="'api:user:create'" icon="CirclePlus" plain type="primary" @click="handleFormOpen(1, 0)">新增</el-button>
        <!-- 修改邀请人 -->
        <el-button v-permission="'api:user:modify_parent'" icon="Edit" plain type="danger" @click="handleShowParentModify">邀请人修改</el-button>
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #login_status="scope">
              <DictTag v-model="scope.row.login_status" dict-type="user_login_status"/>
            </template>

            <template #operations="scope">
              <el-space :size="1" :spacer="spacer">
                <el-button v-permission="'api:user:info'" link type="info" @click="handleFormOpen(0, scope.row.id)">详情</el-button>
                <el-button v-permission="'api:user:update'" link type="primary" @click="handleFormOpen(2, scope.row.id)">编辑</el-button>
                <el-button v-if="scope.row.login_status === 1 && hasPermission('api:user:update_status')" link type="danger" @click="handleSwitchStatus(scope.row, 1)">禁用</el-button>
                <el-button v-if="scope.row.login_status === 0 && hasPermission('api:user:update_status')" link type="warning" @click="handleSwitchStatus(scope.row, 1)">启用</el-button>
              </el-space>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 添加或修改用户对话框 -->
    <UserForm ref="userFormRef" @refresh="handleSearch"/>
    <!-- 邀请人修改弹窗 -->
    <ParentModify ref="parentModifyRef" @refresh="handleSearch"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElDivider, ElLoading, ElMessage, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { computedOperateWidth, pickerShortcuts } from '@/utils';
import { DictTag } from '@/components/dict-tag';
import { hasPermission } from '@/utils/permission.ts';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { userList, userSwitchStatus } from '@/api/api-user.ts';
import { MultipleSelect } from '@/components/other';
import { specialFlagOptions } from '@/utils/global-dict.ts';
import UserForm from './components/user-form.vue';
import ParentModify from './components/parent-modify.vue';
import { useRouter } from 'vue-router';

defineOptions({name: 'user-index'});

const router = useRouter();
const spacer = h(ElDivider, {direction: 'vertical'});

// 查询
const queryFormData = reactive({
  id: undefined,
  account: undefined,
  nickname: undefined,
  login_status: undefined,
  parent_id: undefined,
  parent_account: undefined,
  special_flag: undefined,
  account_flag: undefined,
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'id', label: '用户编号', placeholder: '请输入用户编号', clearable: true},
  {type: 'input', prop: 'account', label: '用户账号', placeholder: '请输入用户账号', clearable: true,},
  {type: 'input', prop: 'nickname', label: '用户昵称', placeholder: '请输入用户昵称', clearable: true,},
  {type: 'input', prop: 'parent_id', label: '邀请人编号', placeholder: '请输入邀请人编号', clearable: true,},
  {type: 'input', prop: 'parent_account', label: '邀请人账号', placeholder: '请输入邀请人账号', clearable: true,},
  {type: 'dict-select', prop: 'login_status', label: '登录状态', placeholder: '请选择登录状态', dictType: 'user_login_status', clearable: true,},
]);
const pickerDate = ref([]);
const specialFlagList = ref<Number[]>([]);

// 列表相关
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('api:user:info')) count += 1
  if (hasPermission('api:user:update')) count += 1
  if (hasPermission('api:user:update_status')) count += 1
  return computedOperateWidth(count);
})

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'uid', label: 'UID', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'id', label: '用户编号', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'account', label: '用户账号', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'invite_code', label: '邀请码', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'parent_id', label: '邀请人编号', width: 120, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'parent_account', label: '邀请人账号', minWidth: 160, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'nickname', label: '用户昵称', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'login_status', label: '登录状态', width: 120, align: 'center', sortable: 'custom'},
  {prop: 'last_login_time', label: '最后登录时间', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'create_time', label: '创建时间', width: 180, align: 'center', sortable: 'custom'},
  {prop: 'update_time', label: '更新时间', width: 180, align: 'center', sortable: 'custom'}
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods
const {handleSelectChange, handleSelectAll, multipleSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 处理其他查询参数
    handleOtherQueryParams();
    // 查询数据
    const {data} = await userList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  pickerDate.value = [];
  specialFlagList.value = [];
  handleResetForm();
};

// 处理其他查询条件
const handleOtherQueryParams = () => {
  // 时间范围参数
  // @ts-ignore
  queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined

  // 特殊状态标识参数
  let specialFlag = 0
  // @ts-ignore
  specialFlagList.value.forEach(it => specialFlag |= it)
  // @ts-ignore
  queryFormData.specialFlag = specialFlag > 0 ? specialFlag : undefined
}

/** 添加/修改操作 */
const userFormRef = ref<any>();
const handleFormOpen = (mode: number, id?: number) => {
  if (mode == 0) {
    router.push({path: '/user/info/' + id});
  } else {
    userFormRef.value?.open(mode, id);
  }
};

/** 邀请人修改弹窗 */
const parentModifyRef = ref<any>();
const handleShowParentModify = () => {
  parentModifyRef.value?.open();
};

/** 更新用户状态 */
const handleSwitchStatus = (row: any, type: number) => {
  if (row == null || row.id <= 0 || !hasPermission('api:user:update_status')) return
  let tipMsg = type === 1 ? '登录状态' : ''
  let reason = type === 1 ? row.forbidLoginNote : '-'
  if (tipMsg.length <= 0) {
    return
  }

  // 弹窗提示
  ElMessageBox.prompt(h('p', null, [
    '您确定要修改账号 ',
    h('span', {style: 'font-weight: bold'}, row.account),
    ` 的 ${tipMsg} ？`,
    h('br'),
    `上次操作原因： ${reason || '-'}`,
  ]), tipMsg, {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入操作原因',
  }).then(({value}) => {
    if (value == null || value.length <= 0) {
      ElMessage.error('请输入操作原因')
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {
      id: row.id,
      type: type,
      reason: value
    }
    // 提交数据
    userSwitchStatus(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};
</script>

<style lang="scss" scoped>
.system-user {
  .name-slot {
    display: flex;
    align-items: center;

    .avatar {
      margin-right: 8px;
      background: unset !important;
    }
  }
}
</style>
